package com.mera.tektronix.csviewer.services

import org.apache.commons.logging.LogFactory
import org.springframework.context.MessageSource

import com.mera.tektronix.csviewer.common.api.*
import com.mera.tektronix.csviewer.common.dto.*
import com.mera.tektronix.csviewer.common.exception.*
import com.mera.tektronix.csviewer.domain.*

class DepartmentService {
	static transactional = true
	private static final log = LogFactory.getLog(DepartmentService.class)
	
	MessageSource messageSource
	CompanyService companyService
	IDepartmentService departmentServiceProxy
	
	def getList(params) {
		log.debug(params)
		
		return departmentServiceProxy.getList().collect{[
			id   : ("_DEP_" + it.id),
			text : it.name
		]}
	}
	
	def getAllList() {
		return departmentServiceProxy.getList().collect {[
			id   : it.id,
			text : it.name
		]}
	}
	
	def getElement(params) {
		log.debug(params)
		
		DepartmentDto dep = null;
		
		try {
			dep = departmentServiceProxy.getDepartmentById(Long.valueOf(params.id));
		} catch(Exception ex) {
			return [
				success      : 'false',
				errorMessage : ex.getLocalizedMessage()
			];
		}
		
		if(dep == null) {
			return [
				success      : 'false',
				errorMessage : "No Department has been found."
			]
		}
		
		return [
			id      : dep.id,
			name    : dep.name,
			email   : dep.email,
			phone   : dep.phone,
			success : 'true'
		];
	}
	
	def addElement(params) {	
		log.debug(params)
		
		CompanyDto company = null;
		
		try {
			company = companyService.getCompany(params);
		} catch(Exception ex) {
			return [
				success      : 'false',
				errorMessage : ex.getLocalizedMessage()
			];
		}
		
		if(company == null) {
			return [
				success      : 'false',
				errorMessage : "No Company has been found."
			]
		} else {
			DepartmentDto dep = new DepartmentDto();
			
			if(params.id != null) dep.id = Long.valueOf(params.id);
			dep.name = params.name;
			dep.email = params.email;
			dep.phone = params.phone;
			dep.companyId = company.id;
			
			try {
				departmentServiceProxy.addDepartment(dep);
			} catch(LogicException lex) {
				def errorList = lex.getErrors();
				
				return [
					success      : 'false',
					errors       : errorList
				]
			}
		}
		
		return [
			success : 'true'
		]
	}
	
	def updateElement(params) {	
		return addElement(params);
	}
	
	def deleteElement(params) {
		log.debug(params)
		
		try {
			departmentServiceProxy.deleteDepartment(Long.valueOf(params.id));
		} catch(Exception ex) {
			return [
				success      : 'false',
				errorMessage : ex.getLocalizedMessage()
			];
		}

		return [success : 'true'];
	}
}
